<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>
    
    ES6 箭头函数及声明特点 - DSRBLOG
    
  </title>
  

  
  
  <link href="atom.xml" rel="alternate" title="DSRBLOG" type="application/atom+xml">
  <link rel="stylesheet" href="asset/css/style.min.css">
  <link rel="stylesheet" href="asset/css/doc.css">
  <script src="asset/app.js"></script>


</head>

<body> <section class="ct-body">
	<div class="container">
		<div class="columns is-variable bd-klmn-columns is-4 is-centered">
			<div class="column is-four-fifths">
				<div class="post-body single-content">
					
					<h1 class="title">
						ES6 箭头函数及声明特点
					</h1>


					<div class="media">
						
						
						<div class="media-content">
							<div class="content">
								<p>
									<span class="date">2022/08/14 16:59 下午</span>
									

									

									<br />
									<span class="tran-tags">Tags:</span>&nbsp;
									
									<a class="tag is-link is-light">#ES6新特性</a>
									

								</p>
							</div>
						</div>

					</div>
				</div>
				<article class="markdown-body single-content">
					<h2><a id="%E5%A3%B0%E6%98%8E%E5%87%BD%E6%95%B0" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>声明函数</h2>
<ul>
<li>
<p><strong>ES6</strong> 允许使用「箭头」（=&gt;）定义函数</p>
<pre class="line-numbers"><code class="language-js">//原函数
let fn = function(a,b){}

//箭头函数
let fn = (a,b) =&gt; {}
</code></pre>
</li>
</ul>
<h2><a id="%E7%89%B9%E6%80%A7" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>特性</h2>
<ol>
<li>
<p><code>this</code>是静态的，<code>this</code>始终指向<strong>函数声明时所在作用域</strong>下的<code>this</code>的值</p>
<ol>
<li>声明普通函数
<pre class="line-numbers"><code class="language-js">function getName(){
    console.log(this.name);
}
</code></pre>
</li>
<li>声明箭头函数
<pre class="line-numbers"><code class="language-js">let getName2 = () =&gt; {
    console.log(this.name);
}
</code></pre>
</li>
<li>调用函数
<pre class="line-numbers"><code class="language-js">//设置window对象的name属性
window.name = '测试';
const test = {
    name: &quot;TEST&quot;
}

//直接调用
getName(); //输出'测试'
getName2(); //输出'测试'

//call方法
getName.call(test); //输出'TEST'
getName2.call(test); //输出'测试'
</code></pre>
</li>
</ol>
</li>
<li>
<p>不能作为构造函数实例化对象</p>
<pre class="line-numbers"><code class="language-js">let Person = (name,age)=&gt;{
    this.name = name;
    this.age = age;
}

let me = new Person('He', 20);
console.log(me);//报错（Person is not a constructor）
</code></pre>
</li>
<li>
<p>不能使用<code>argumants</code>变量</p>
<p><em>argumants：</em> 特殊函数，用于保存实参</p>
<pre class="line-numbers"><code class="language-js">let fn = () =&gt; {
    console.log(arguments);
}

fn(1,2,3);//arguments is not defined
</code></pre>
</li>
<li>
<p>箭头函数的简写</p>
<ol>
<li>
<p>省略小括号（当形参有且只有一个的时候）</p>
<pre class="line-numbers"><code class="language-js">//原箭头函数
let add = (n) =&gt; {
    return n + n;
}

//简写箭头函数
let add = n =&gt; {
    return n + n;
}
</code></pre>
</li>
<li>
<p>省略花括号（当代码块只有一条语句的时候）</p>
<pre class="line-numbers"><code class="language-js">//原箭头函数
let pow = (n) =&gt; {
    return n * n;
}

//简写箭头函数
//此时return必须省略，语句的执行结果就是函数的返回值
let pow = (n) =&gt; n * n;
</code></pre>
</li>
</ol>
</li>
</ol>
<h2><a id="%E5%AE%9E%E8%B7%B5" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>实践</h2>
<h3><a id="%E6%A1%88%E4%BE%8B%E4%B8%80" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>案例一</h3>
<ul>
<li>
<p>点击div 2s后颜色变成「粉色」</p>
<ol>
<li>
<p>原函数</p>
<pre class="line-numbers"><code class="language-js">//获取元素
let ad = document.getElementById('ad');

//绑定（监听）事件
ad.addEventListener(&quot;click&quot;,function(){

    //保存this的值，this 指向事件源 ad
    let _this = this;
    
    //定时器
    setTimeout(function(){
    
        //修改背景颜色
        this.style.background = 'pink';//报错，this 无法指向 ad
        
        _this.style.background = 'pink';
    }, 2000);
})
</code></pre>
</li>
<li>
<p>箭头函数</p>
<pre class="line-numbers"><code class="language-js">//获取元素
let ad = document.getElementById('ad');

//绑定（监听）事件
ad.addEventListener(&quot;click&quot;,function(){
       
    //定时器
    setTimeout(() =&gt; {
    
        //修改背景颜色
        this.style.background = 'pink'; //this 指向箭头函数所在作用于的事件源 ad
    }, 2000);
})
</code></pre>
</li>
</ol>
</li>
</ul>
<h3><a id="%E6%A1%88%E4%BE%8B%E4%BA%8C" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>案例二</h3>
<ul>
<li>
<p>从数组中返回偶数的元素</p>
<ol>
<li>原函数</li>
</ol>
<pre class="line-numbers"><code class="language-js">const arr = [1,6,9,10,100,25];

const result = arr.filter(function(item){
    if(item % 2 === 0){
            return true;
    }else{
            return false;
    }
});
</code></pre>
<ol start="2">
<li>箭头函数</li>
</ol>
<pre class="line-numbers"><code class="language-js">const arr = [1,6,9,10,100,25];

const result = arr.filter(item =&gt; item % 2 === 0); 
//retrun被简写，执行结果就是函数的返回值，当item除2余数为0时返回true
</code></pre>
<p><strong><code>filter()</code>方法：</strong> 创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素</p>
</li>
</ul>
<h2><a id="%E6%80%BB%E7%BB%93" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>总结</h2>
<ol>
<li>箭头函数适合与<code>this</code>无关的回调 <strong>（如定时器、数组的方法回调）</strong></li>
<li>箭头函数不适合与<code>this</code>有关的回调 <strong>（如DOM元素的事件回调、对象的方法）</strong></li>
</ol>

				</article>
				<div class="comments-wrap">
					<div class="share-comments">
						

						

						
					</div>
				</div><!-- end comments wrap -->
			</div>
		</div><!-- end columns -->
	</div><!-- end container -->
</section>  














<script src="asset/prism.js"></script>









</body>

</html>